import { getCode } from "../../service/login";
import { hyLoginReqInstance } from "../../service/index";

Page({
  async onLoad() {
    // 判断是否有token
    const token = wx.getStorageSync("token") || "";
    // 2. 判断token是否过期
    const res = await hyLoginReqInstance.post({
      url: "/auth",
      header: {
        token,
      },
    });

    if (token && res.message === "已登录") {
      console.log("请求嵌套的数据");
    } else {
      this.handlerLogin();
    }
  },

  async handlerLogin() {
    // 1. 获取code
    const code = await getCode();

    // 3. 使用code换取token
    const res = await hyLoginReqInstance.post({
      url: "/login",
      data: {
        code,
      },
    });

    wx.setStorageSync("token", res.token);
  },

  // 第一种写法
  /* handlerLogin() {
        // 1. 获取code
        wx.login({
            success: res => {
                console.log(res)
                const code = res.code
                // 2. 将这个code发送给自己的服务器
                wx.request({
                    url: 'http://123.207.32.32:3000/login',
                    data: {
                        code
                    },
                    method: 'post',
                    success: res => {
                        const token = res.data.token
                        wx.setStorageSync('token', token)
                    }
                })
            }
        })
    } */
});
